const api = require('./api.js');
/**
 * 发起网络请求
 * @param {Object} e 
 * @param {String} e.url 请求路径
 * @param {String} e.method 请求方式
 * @param {Object} e.data 请求体
 */
const request = (url,data,method = 'POST') => new Promise((t,f) => {
    //const uri = 'https://bishe.my2171.com';
     const uri = 'http://127.0.0.1:8081';
    wx.request({
        url: uri + url,
        data,method,
        header: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success:(res) => {
            t(res)
        }
    })
})

// 获取 open_id
const getOpenId = () => new Promise((t,f) => {
    api.getStorage('userInfo').then(info => {
        if (info) t(info.open_id);
        else {
            wx.login({
                success(e) {
                  request('/auth/getOpenId',{ code: e.code}).then(res => {
                      t(res.data.openid);
                  })
                   
                },
            })
        }
    })
})

// 获取用户信息登录
const getUserInfo = () => new Promise((t,f) => {
    getOpenId().then(open_id => {
      api.getStorage('role').then(ans=>{
      request('/auth/getInfo',{ openid:open_id,role:ans}).then(res => {
            api.hide();
            let { code,msg,data } = res.data;
            switch (code) {
                case 200:
                    t(data);
                    api.setStorage('userInfo',data);
                    break;
                case 501: t(null); break;
                default: api.showToast(msg,'none');
            }
        })
    })
  })
})

//教师使用手机号登录
const getTeacherInfo = (phone) => new Promise((t,f) => {
  getOpenId().then(open_id => {
    request('/teacher/getTeacherInfo',{ open_id:open_id,account:phone}).then(res => {
      api.hide();
      let { code,msg,data } = res.data;
      switch (code) {
          case 200:
              t(data);
              api.setStorage('userInfo',data);
              break;
          case 501: t(null); break;
          default: api.showToast(msg,'none');
      }
  })
})
})

// 获取系部列表
const getSdeptList = () => new Promise((t,f) => {
    request('/student/getSdepts').then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 获取班级列表
 * @param {*} sdept_id 系部 id
 */
const getClassBySdept = (sdept_id) => new Promise((t,f) => {
    request('/student/getClassBySdept', { sdept_id }).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})



// 用户注册
const register = (e) => new Promise((t,f) => {
    request('/student/register',e).then(res => {
        let { code,msg } = res.data;
        switch (code) {
            case 200:
                api.hide();
                api.showToast('注册成功','success');
                setTimeout(() => {
                    api.navigateBack();
                }, 1500);
                break;
            default: api.showToast(msg,'none');
        }
    })
})

// 获取课题分类
const getTypes = () => new Promise((t,f) => {
    request('/topic/getTypes').then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

// 获取课题列表
const getTopic = (e) => new Promise((t,f) => {
    request('/topic/getList', e).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

// 获取教师课题列表
const getTeacherTopic = (e) => new Promise((t,f) => {
  request('/topic/getTeacherTopic', e).then(res => {
      let { code,msg,data } = res.data;
      switch (code) {
          case 200: t(data); break;
          default: api.showToast(msg,'none');
      }
  })
})
//教师发布课题
const addTopic=(filePath,data)=> new Promise((t,f)=>{
    wx.uploadFile({
        url: 'http://localhost:8081/topic/addTopic',
        name: 'file',
        filePath,
        formData: data,
        success: (res) => {
            let { code,msg,data } = JSON.parse(res.data);
            switch (code) {
                case 200: t(data); break;
                default: api.showToast(msg,'none');
            }
        },
    })  
})

/**
 * 搜索课题
 * @param {*} title 关键字 
 */
const searchTopic = (title) => new Promise((t,f) => {
    request('/topic/search',{ title }).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 获取课题详情
 * @param {*} id 课题 id
 */
const getTopicDetails = (id) => new Promise((t,f) => {
    request('/topic/getDetails',{ id }).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})



/**
 * 获取报名课题权限
 * @param {*} open_id open_id
 */
const getSignRoot = (open_id) => new Promise((t,f) => {
    getUserInfo(open_id).then(res => {
        if (res.team_id) {
            getTeamInfo(res.team_id).then(team => {
                if (team.topic_state === 0) t({ code: 500, msg: '小组已报名其他课题' });
                else if (team.leader_id === open_id) t({ code: 200, msg: 'ok' });
                else t({ code: 501, msg: '请联系组长完成报名' });
            })
        } else t({ code: 502, msg: '请加入小组后报名课题' });
    },ref => t({ code: 503, msg: '服务异常' }));
})

/**
 * 课题报名
 * @param {*} e { 用户 open_id, 课题 id } 
 */
const sign = (e) => new Promise((t,f) => {
    request('/topic/subscribe',e).then(res => {
        let { code,msg } = res.data;
        switch (code) {
            case 200: t(); break;
            default: api.showToast(msg,'none');
        }
    })
})


/**
 * 获取公告列表
 * @param {*} e 参数
 */
const getNoticeList = (e) => new Promise((t,f) => {
    request('/notice/getStudentNotice',e).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 获取公告详情
 * @param {*} id 公告 id
 */
const getNoticeDetails = (id) => new Promise((t,f) => {
    request('/notice/getNoticeDetails',{ id }).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 修改头像
 * @param {*} e open_id avatar
 */
const editAvatar = (e) => new Promise((t,f) => {
    request('/student/editAvatar',e).then(res => {
        let { code,msg } = res.data;
        switch (code) {
            case 200: t(); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 修改姓名
 * @param {*} e open_id nickname
 */
const editNickname = (e) => new Promise((t,f) => {
    request('/student/editNickname',e).then(res => {
        let { code,msg } = res.data;
        switch (code) {
            case 200: t(); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 上传文件
 * @param {*} filePath 文件 url
 * @param {*} type 文件类型 0-图片 1-文档
 */
const upFile = (filePath,type=0) => new Promise((t,f) => {
    wx.uploadFile({
        url: 'https://upload.my2171.com/file/up',
        name: 'file',
        filePath,
        formData: {
            type,
            itemName: 'bishe'
        },
        success: (res) => {
            let { code,msg,data } = JSON.parse(res.data);
            switch (code) {
                case 200: t(data); break;
                default: api.showToast(msg,'none');
            }
        },
    })  
})

/**
 * 获取我的周报
 * @param {*} e open_id page pagesize
 */
const getMyReport = (e) => new Promise((t,f) => {
    request('/report/getMyReport',e).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 获取周报详情
 * @param {*} id 周报 id
 */
const getReportDetails = (id) => new Promise((t,f) => {
    request('/report/getDetails',{ id }).then(res => {
        let { code,msg,data } = res.data;
        switch (code) {
            case 200: t(data); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 获取教师周报列表
 * @param {*} open_id 教师id
 */
const getReportList = (open_id) => new Promise((t,f) => {
  request('/report/getReportList',{ open_id }).then(res => {
      let { code,msg,data } = res.data;
      switch (code) {
          case 200: t(data); break;
          default: api.showToast(msg,'none');
      }
  })
})

/**
 * 发布周报
 * @param {*} e 见接口文档
 */
const addReport = (e) => new Promise((t,f) => {
    request('/report/add',e).then(res => {
        let { code,msg } = res.data;
        switch (code) {
            case 200: t(); break;
            default: api.showToast(msg,'none');
        }
    })
})

/**
 * 获取教师周报列表
 * @param {*} open_id 教师id
 */
const getSubscribeList = (open_id) => new Promise((t,f) => {
  request('/teacher/getSubscribe',{ open_id }).then(res => {
      let { code,msg,data } = res.data;
      switch (code) {
          case 200: t(data); break;
          default: api.showToast(msg,'none');
      }
  })
})

/**
 * 教师处理学生预约
 * @param {*} teacher_id 教师id
 */
const hanleSubscribe = (teacher_id,topic_id,state) => new Promise((t,f) => {
  request('/teacher/toExamine',{ teacher_id,topic_id,state }).then(res => {
      let { code,msg,data } = res.data;
      switch (code) {
          case 200: t(data); break;
          default: api.showToast(msg,'none');
      }
  })
})

/**
 * 获取管理员审核列表
 * @param {*} e 参数
 */
const getInspectList = (e) => new Promise((t,f) => {
  request('/topic/getInspect',e).then(res => {
      let { code,msg,data } = res.data;
      switch (code) {
          case 200: t(data); break;
          default: api.showToast(msg,'none');
      }
  })
})

//管理员审核课题
const toExmaine=(data)=> new Promise((t,f)=>{
  request('/topic/examine',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//管理员增加课题分类
const addTopicType=(data)=> new Promise((t,f)=>{
  request('/topic/addType',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//管理员删除课题分类
const delTopicType=(data)=> new Promise((t,f)=>{
  request('/topic/delType',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//管理员修改课题分类
const updateTopicType=(data)=> new Promise((t,f)=>{
  request('/topic/updateType',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//管理员修改课题分类
const getStations=()=> new Promise((t,f)=>{
  request('/teacher/getStations').then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//增加职位
const addStation=(data)=> new Promise((t,f)=>{
  request('/teacher/addStation',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//删除职位
const delStation=(data)=> new Promise((t,f)=>{
  request('/teacher/delStation',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//职位修改
const editStation=(data)=> new Promise((t,f)=>{
  request('/teacher/editStation',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
/** =============院系======================*/
const editDepth=(data)=> new Promise((t,f)=>{
  request('/student/editSdept',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
const addDepth=(data)=> new Promise((t,f)=>{
  request('/student/addSdept',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
const delDepth=(data)=> new Promise((t,f)=>{
  request('/student/delSdept',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
/** =============班级======================*/
const editClass=(data)=> new Promise((t,f)=>{
  request('/student/editClass',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
const addClass=(data)=> new Promise((t,f)=>{
  request('/student/addClass',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
const delClass=(data)=> new Promise((t,f)=>{
  request('/student/delClass',data).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
const getStudentList=()=> new Promise((t,f)=>{
  request('/student/getList').then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
const getTeacherList=()=> new Promise((t,f)=>{
  request('/teacher/getList').then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})

const regiterTeacher=(info)=> new Promise((t,f)=>{
  request('/teacher/addTeacher',info).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
//获取学生课题
const getStuTopic=(e)=> new Promise((t,f)=>{
  request('/student/getStuTopic',e).then(res=>{
    let {code,msg,data}=res.data;
    switch(code){
      case 200:t(data);break;
      default:api.showToast(msg,'none');
    }
  })
})
export {
    request,            // 发起网络请求
    /**=========用户============== */
    getOpenId,          // 获取 open_id
    getUserInfo,        // 获取用户信息（登录）
    register,           // 用户注册
    editAvatar,         // 修改头像
    editNickname,       // 修改姓名
    upFile,             // 上传文件
    /**=============课题===================== */
    getTypes,           // 获取课题分类
    getTopic,           // 获取课题列表
    getTeacherTopic,    //获取教师课题列表
    addTopic,           //添加课题
    searchTopic,        // 搜索课题
    getTopicDetails,    // 获取课题详情
    getSignRoot,        // 获取报名课题权限
    sign,               // 课题报名
    /**=============公告======================== */
    getNoticeList,      // 获取公告列表
    getNoticeDetails,   // 获取公告详情
    /**==============周报======================= */
    getMyReport,        // 获取我的周报
    getReportDetails,   // 获取周报详情
    addReport,          // 发布周报
    getReportList,      //周报列表
    /**=============学生================= */
    getStudentList,     //获取学生列表
    hanleSubscribe,      //处理学生订阅课题
    getStuTopic,        //获取我的课题
    /**==============管理员===================== */
    getInspectList,     //获取管理员审核课题的列表
    toExmaine,  //管理审核课题
    addTopicType, //管理员增加课题分类
    delTopicType, //管理员删除课题分类
    updateTopicType,//更新课题分类
  /** ===============教师职位====================*/
    getSubscribeList,   //获取学生预列表
    getTeacherList,
    getTeacherInfo, //用于第一次登录
    regiterTeacher,
    getStations, 
    addStation,
    delStation,
    editStation,
    /**===============院系===================== */
    getSdeptList, // 获取系部列表
    addDepth,
    delDepth,
    editDepth,
    /**===============班级================= */
    getClassBySdept,    // 获取班级列表
    addClass,
    delClass,
    editClass,
}